<template>
  <el-dialog v-model="visible" :title="title" width="1000" show-footer show-zoom resize :close-on-click-modal="false"
    :close-on-press-escape="false" @close="close">
    <template #default>
      <el-form ref="formRef" :rules="rules" :model="form" label-align="right" label-width="80" size="default"
        :label-position="handleType == 'view' ? 'left' : 'top'">
        <el-row :gutter="20">
          <el-col :span="8" v-if="handleType != 'add'">
            <el-form-item label="替换单号" prop="location_code">
              {{ form.product_replace_order_no }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="仓库" prop="warehouse_id">
              <template v-if="handleType == 'view'">{{ form.warehouse_name }}</template>
              <SelectWarehouse v-else class="w-full" v-model="form.warehouse_id" :disabled="form.id" placeholder="请输入调出仓"
                @change="changeWarehouse">
              </SelectWarehouse>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="审批单号" prop="verify_order_no">
              <template v-if="handleType == 'view'">{{ form.verify_order_no }}</template>
              <el-input v-else v-model="form.verify_order_no" placeholder="请输入审批单号" :disabled="handleType == 'view'" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <vxe-table :data="form.detail" :round="true" height="300">
        <vxe-column title="原SKU">
          <template #default="{ row }">
            <template v-if="handleType == 'view'">{{ row.origin_sku }}</template>
            <el-input v-else v-model="row.origin_sku" placeholder="输入SKU" @change="changeSkU(row, 'old')"
              :disabled="handleType == 'view' || disabled" />
          </template>
        </vxe-column>
        <vxe-column title="货位">
          <template #default="{ row }">
            <template v-if="handleType == 'view'">{{ row.origin_location_code }}</template>
            <template v-else>
              <el-select v-if="row.origin_location?.length" class="w-full" v-model="row.origin_location_id"
                placeholder="货位" @change="changeLocation($event, row)" :disabled="handleType == 'view' || disabled">
                <el-option v-for="item in row.origin_location" :key="item.location_id" :label="item.location_code"
                  :value="item.location_id">
                </el-option>
              </el-select>
              <el-select v-else class="w-full" v-model="row.origin_location_id" placeholder="货位"
                :disabled="handleType == 'view' || disabled">
                <el-option v-for="item in locationAllData" :key="item.location_id" :label="item.location_code"
                  :value="item.location_id">
                </el-option>
              </el-select>
            </template>
          </template>
        </vxe-column>
        <vxe-column title="货主">
          <template #default="{ row }">
            <template v-if="handleType == 'view'">{{ row.owner_name }}</template>
            <template v-else>
              <template v-if="row.owner?.length">
                <el-select class="w-full" v-model="row.owner_id" placeholder="货位"
                  :disabled="handleType == 'view' || disabled" @change="changeOwner($event, row)">
                  <el-option v-for="item in row.owner" :key="item.owner_id" :label="item.owner_name"
                    :value="item.owner_id">
                  </el-option>
                </el-select>
              </template>
              <template v-else>
                <select-personnel v-model="row.owner_id" placeholder="货主" :disabled="handleType == 'view' || disabled"
                  @change="changeOwner($event, row)"></select-personnel>
              </template>
            </template>
          </template>
        </vxe-column>
        <vxe-column field="origin_num" title="货位可替换数量">
          <template #default="{ row }">
            {{ row.origin_num || '--' }}
          </template>
        </vxe-column>
        <vxe-column title="替换后SKU">
          <template #default="{ row }">
            <template v-if="handleType == 'view'">{{ row.replace_sku }}</template>
            <el-input v-else v-model="row.replace_sku" placeholder="输入SKU" @change="changeSkU(row, 'new')"
              :disabled="handleType == 'view' || disabled" />
          </template>
        </vxe-column>
        <vxe-column title="替换货位">
          <template #default="{ row }">
            <template v-if="handleType == 'view'">{{ row.replace_location_code }}</template>
            <template v-else>
            <el-select v-if="row.replace_location?.length" class="w-full" v-model="row.replace_location_id"
              placeholder="货位" :disabled="handleType == 'view'">
              <el-option v-for="item in row.replace_location" :key="item.location_id" :label="item.location_code"
                :value="item.location_id">
              </el-option>
            </el-select>
            <el-select v-else class="w-full" v-model="row.replace_location_id" placeholder="货位"
              :disabled="handleType == 'view'">
              <el-option v-for="item in locationAllData" :key="item.location_id" :label="item.location_code"
                :value="item.location_id">
              </el-option>
            </el-select>
          </template>
          </template>
        </vxe-column>
        <vxe-column title="替换数量">
          <template #default="{ row }">
            <template v-if="handleType == 'view'">{{ row.replace_num }}</template>
            <el-input v-else v-model="row.replace_num" placeholder="调拨数量" :disabled="handleType == 'view' || disabled" />
          </template>
        </vxe-column>
        <vxe-column field="remark" title="备注">
          <template #default="{ row }">
            <template v-if="handleType == 'view'">{{ row.remark }}</template>
            <el-input v-else v-model="row.remark" placeholder="备注" :disabled="handleType == 'view' || disabled" />
          </template>
        </vxe-column>
        <vxe-column field="opearn" title="操作" width="100" v-if="handleType != 'view' || !disabled">
          <template #default="{ row, rowIndex }">
            <el-link class="mr-2" size="small" type="primary" @click="addRow">新增</el-link>
            <el-link size="small" type="danger" @click="deleteRow(rowIndex)">删除</el-link>
          </template>
        </vxe-column>
      </vxe-table>
    </template>

    <template #footer>
      <template v-if="handleType == 'view'">
        <div class="flex justify-center py-2">
          <el-button type="" @click="close">关 闭</el-button>
        </div>
      </template>
      <div class="flex justify-center py-2" v-else>
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" :loading="loading" @click="save(formRef)">保 存</el-button>
      </div>

    </template>
  </el-dialog>
</template>
<script setup name="ComModal">
import { getProductReplaceDetail, saveProductReplace, updateProductReplace } from '../api/index'
import { getSKULocation, getLocationData } from '@/api/public'
import { reactive, ref, toRefs } from 'vue'
import { ElMessage } from 'element-plus'
import SelectWarehouse from '@/components/SelectWarehouse'

const visible = ref(false)
const loading = ref(false)
const formRef = ref(null)
const emits = defineEmits(['query'])

const props = defineProps({
  wareDataList: {
    type: Array,
    default: [],
  },
})

const data = reactive({
  form: {},
  title: '新增',
  handleType: null,
  rules: {
    warehouse_id: [{
      required: true, message: '请选择仓库', trigger: 'blur'
    }],
    verify_order_no: [{
      required: true, message: '请输入审批单号', trigger: 'blur'
    }],
  },
  locationAllData: [],
  disabled: false
})
const { form, title, handleType, rules, locationAllData, disabled } = toRefs(data)

const statusMap = new Map([
  ['add', '新增'],
  ['edit', '编辑'],
  ['view', '查看'],
])

const open = (type, id) => {
  title.value = statusMap.get(type)
  handleType.value = type
  disabled.value = false
  visible.value = true
  if (id) getDetail(id)
}

const initForm = () => {
  form.value = getForm()
}
// 初始化
const getForm = () => {
  return {
    detail: [
      {
        origin_sku: "",//原sku
        origin_custom_sku: "",//原自定义sku
        origin_base_sku_code: "",//原商品编码
        origin_location_id: null,//原货位id
        origin_num: "",//原货位可替换数量
        replace_sku: "",//替换sku
        replace_custom_sku: "",//替换自定义sku
        replace_base_sku_code: "",//替换商品编码
        replace_location_id: null,//替换货位id
        replace_num: "",//货位替换数量
        remark: "",//备注
        location: [],
        location01: [],
      }
    ]
  }
}

onMounted(() => {
  initForm()
})

const getDetail = async (id) => {
  try {
    const res = await getProductReplaceDetail({
      id
    })
    form.value = res.data
    disabled.value = res.data.status >= 3 || handleType != 'view'
  } catch (e) {
    throw Error(e)
  }
}

const getLocationList = async () => {

  try {
    const res = await getLocationData({
      warehouse_id: form.value.warehouse_id
    })
    locationAllData.value = res.data.map(i => {
      i.location_id = i.id
      return i
    })
  } catch (e) {
    throw Error(e)
  }
}

const changeWarehouse = async (val) => {
  if (!form.value.warehouse_id) {
    return
  }
  getLocationList()
}

const addRow = async () => {
  form.value.detail.push({
    origin_sku: "",//原sku
    origin_custom_sku: "",//原自定义sku
    origin_base_sku_code: "",//原商品编码
    origin_location_id: null,//原货位id
    origin_num: "",//原货位可替换数量
    replace_sku: "",//替换sku
    replace_custom_sku: "",//替换自定义sku
    replace_base_sku_code: "",//替换商品编码
    replace_location_id: "",//替换货位id
    replace_num: "",//货位替换数量
    remark: "",//备注
    origin_location: [],
    replace_location: [],
  })
}

const deleteRow = (index) => {
  if (form.value.detail.length <= 1) return
  form.value.detail.splice(index, 1)
}

const changeSkU = async (row, type) => {
  if (!row.origin_sku && type == 'old') {
    ElMessage.error('输入原sku')
    return
  }
  if (!row.replace_sku && type == 'new') {
    ElMessage.error('输入替换后sku')
    return
  }
  if (!form.value.warehouse_id) {
    ElMessage.error('请选择仓库')
    return
  }
  try {
    const res = await getSKULocation({
      sku: type == 'old' ? row.origin_sku : row.replace_sku,
      warehouse_id: form.value.warehouse_id,
      type: 1
    })
    if (type == 'old') {
      row.origin_sku = res.data.sku
      row.origin_location = res.data.location
      row.owner = res.data.owner
      row.owner_id = ''
      row.origin_custom_sku = res.data.custom_sku || '32323sses'
      row.origin_base_sku_code = res.data.base_sku_code
    } else {
      row.replace_custom_sku = res.data.sku
      row.replace_location = res.data.location || []
      row.custom_sku = res.data.custom_sku || '32323sses'
      row.replace_base_sku_code = res.data.base_sku_code
      console.log(row.replace_location)

    }
    if (res.data.location?.length == 0) {
      getLocationList()
    }
  } catch (e) {
    throw Error(e)
  }
}

const changeLocation = (val, row) => {
  const checkItem = row.origin_location.find(item => item.location_id == val)
  if (checkItem == undefined) return
  row.origin_num = checkItem.num
}

const changeOwner = (val, row) => {
  const checkItem = row.owner.find(item => item.owner_id == val)
  if (checkItem == undefined) return
  row.owner_name = checkItem.owner_name
  row.origin_num = checkItem.num
}

const save = () => {
  if (!formRef.value) return
  formRef.value.validate((valid) => {
    if (valid) {
      loading.value = true
      console.log(form.value)
      if (form.value.id) {
        updateProductReplace(form.value)
          .then((res) => {
            ElMessage.success(res.message)
            emits('query')
            close()
          })
          .finally((e) => {
            loading.value = false
          })
      } else {
        saveProductReplace(form.value)
          .then((res) => {
            ElMessage.success(res.message)
            emits('query')
            close()
          })
          .finally((e) => {
            loading.value = false
          })
      }
    }
  })
}
const close = () => {
  initForm()
  visible.value = false
}
defineExpose({ open })
</script>
<style lang="scss" scoped>
.borderNone {
  :deep(.el-input__wrapper) {
    border: none;
    box-shadow: none
  }
}
</style>
